package com.shuangti.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuangti.gateway.server.AuthService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.nio.charset.StandardCharsets;



public class AuthFilter extends AbstractGatewayFilterFactory<AuthFilter.Config> implements GlobalFilter {


    private final AuthService authService;


    public AuthFilter(AuthService authService){
        super(Config.class);
        this.authService = authService;
    }

    @Override
    public GatewayFilter apply(Config config){
        return((exchange, chain) -> {
            ServerHttpRequest request = (ServerHttpRequest) exchange.getRequest();

            //检查请求头中是否含有token信息
            String token = request.getHeaders().getFirst("AccessKeyToken");

            //若Token不存在，则将请求转发到认证服务器
            if(token == null || token.isEmpty()){
                return forwardToAuthServer(exchange,chain);
        }else{
                //若Token存在，则在redis里查询对不对
                /*
                 @TODO
                 */
                return chain.filter(exchange);
            }
    });
    }


    private Mono<Void> forwardToAuthServer(ServerWebExchange exchange, GatewayFilterChain chain){
        String token;
        return DataBufferUtils.join(exchange.getRequest().getBody())
                .flatMap(dataBuffer -> {
                    byte[] bytes = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(bytes);
                    DataBufferUtils.release(dataBuffer);
                    String requestBody = new String(bytes, StandardCharsets.UTF_8);

                    ObjectMapper objectMapper = new ObjectMapper();
                    try{
                        JsonNode jsonNode = objectMapper.readTree(requestBody);
                        String username = jsonNode.get("username").asText();
                        String password = jsonNode.get("password").asText();

                        return authService.getToken(username, password)
                                .onErrorResume(e -> {
                                    ServerHttpResponse httpResponse = (ServerHttpResponse) exchange.getResponse();
                                    httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                                    String result = "error";
                                    return Mono.empty();
                                })
                                .then(chain.filter(exchange));

                    } catch (Exception e) {
                        return Mono.error(new RuntimeException(e));
                    }
                });
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return null;
    }


    @Data
    public static class Config{
        private boolean enabled = true;
    }
}
